package homework_2;
import java.util.*;
import java.io.*;
public class SortStudnetScore {
	public static ArrayList<Student> studentList = new ArrayList<Student>();
	public static void quicksort(int left, int right) {
		if (left > right) return;
		
		int i = left;
		int j = right;
		Student temp = studentList.get(left);
		while (i != j) {
			while(studentList.get(j).getTotalScore() <= temp.getTotalScore() && i<j) j--;
			if (i < j) studentList.set(i++, studentList.get(j));
			while(studentList.get(i).getTotalScore() >= temp.getTotalScore() && i<j) i++;
			if (i < j) studentList.set(j--, studentList.get(i));
		}
		
		studentList.set(i, temp);
		
		quicksort(left, i-1);
		quicksort(i+1, right);
	}
	
	public static void main(String[] args) throws IOException{
		// TODO Auto-generated method stub
		
		FileReader input = new FileReader("NameTable.txt");
		BufferedReader reader = new BufferedReader(input);
		File output = new File("ScoreTable.txt");
		FileOutputStream fos = new FileOutputStream(output, true);
		OutputStreamWriter osw = new OutputStreamWriter(fos);
		BufferedWriter writer = new BufferedWriter(osw);
		String line = null;
		while ((line = reader.readLine()) != null) {
			String[] str = line.split(",");	
			studentList.add(new Student(str[0], str[1]));
		}
		for (Student stu : studentList) {
			writer.write(stu.scoreTableLine());
			writer.flush();
		}
		writer.close();
		osw.close();
		fos.close();
		reader.close();
		input.close();
		
		quicksort(0, studentList.size()-1);
		
		FileWriter sortedOutput = new FileWriter("SortedScore.txt");
		BufferedWriter sortedWriter = new BufferedWriter(sortedOutput);
		for( Student s : studentList) {
			sortedWriter.write(s.sortedScoreLine());
			sortedWriter.flush();
		}
		sortedWriter.write("平均成绩");
		sortedWriter.flush();
		int[] totalEachScore = Student.getTotalEachScore();
		for(int i : totalEachScore) {
			sortedWriter.write("," + (float)i/studentList.size());
		}
		sortedWriter.flush();
		sortedWriter.close();
		sortedOutput.close();
	}

}
